package com.dkm.orproject.dkmoa.action;

import com.alibaba.fastjson.JSON;
import com.dkm.orproject.dkmoa.domain.OaCar;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.service.OaCarService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.Tools;
import io.swagger.annotations.*;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName : OaCarAction  //类名
 * @Description : 车辆action  //描述
 * @Author : 易嵘  //作者
 * @Date: 2021-01-20 09:22  //时间
 */
@RestController
@RequestMapping("OaCarAction")
@Api(tags = "车辆管理")
public class OaCarAction {

    /**
     * 车辆服务接口
     */
    @Resource
    OaCarService carService;

    /**
     * 工具类
     */
    @Resource
    Tools tools;


    /**
     * 回调值
     */
    int row = 0;

    /**
     * 日志
     */
    OaLog log;

    /**
     * 登陆人
     */
    OaPersonnel personnel;

    /**
     * 回调map
     */
    Map<String, Object> map;

    /**
     * 分页查询
     *
     * @param carName   车辆名称 用于条件查询
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param page      当前页数
     * @param limit     显示的行数
     * @return 车辆集
     */
    @ApiOperation(value = "车辆分页查询接口", notes = "车辆分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "carName", value = "车辆名称（模糊）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "显示行数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "OK", response = OaCar.class),
    })
    @UserLoginToken
    @GetMapping("findAll")
    public Map<String, Object> findAll(String carName,
                                       String startTime,
                                       String endTime,
                                       Integer page,
                                       Integer limit,
                                       HttpServletRequest request) {
        //获取当前操作人信息
        rowMap(request);
        //判断操作人是否存在
        if (ObjectUtils.isEmpty(personnel)) {
            return null;
        }
        try {
            List<OaCar> votes;
            Long rowCount;
            //批量查询分页
            votes = carService.findAll(carName, startTime, endTime, page, limit);
            //查询总行数
            rowCount = carService.rowCount(carName, startTime, endTime);

            //格式化返回参数
            return Tools.maps(votes, rowCount);
        } catch (Exception e) {
            //报错信息收集
            addErrorLog(request, "车辆分页查询", e);
        }
        return null;

    }

    /**
     * id查询
     *
     * @param id 车辆主键
     * @return 车辆模型
     */
    @ApiOperation(value = "id查询", notes = "id查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "车辆id", dataType = "Long", paramType = "path", required = true),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "OK", response = OaCar.class),
    })
    @UserLoginToken
    @GetMapping("findById/{id}")
    public Map<String, Object> findById(@PathVariable("id") Long id, HttpServletRequest request) {
        //获取当前操作人
        rowMap(request);
        //判断当前操作人是否存在
        if (ObjectUtils.isEmpty(personnel)) {
            return tools.rowMap(map, 0, null);
        }
        try {
            //id查询
            map.put("data",carService.selectByPrimaryKey(id));
            map.put("code", 1);
        } catch (Exception e) {
            //报错信息收集
            addErrorLog(request, "车辆id查询", e);
        }
        return map;
    }

    /**
     * 车辆新增
     *
     * @param car     车辆模型
     * @param request 服务器请求
     * @return 回调函数
     */
    @ApiOperation(value = "车辆新增", notes = "车辆新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pkCarId", value = "车辆id", dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name = "carTypeId", value = "车辆类型id", dataType = "Long",paramType = "query", required = true),
            @ApiImplicitParam(name = "carName", value = "车辆名称", dataType = "String",paramType = "query", required = true),
            @ApiImplicitParam(name = "carPlate", value = "车牌", dataType = "String",paramType = "query", required = true),
            @ApiImplicitParam(name = "carBrand", value = "厂牌", dataType = "String",paramType = "query", required = true),
            @ApiImplicitParam(name = "carTime", value = "生产日期", dataType = "Date",paramType = "query", required = true),
            @ApiImplicitParam(name = "carPurchase", value = "购入日期", dataType = "Date",paramType = "query", required = true),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "操作成功"),
    })
    @UserLoginToken
    @PostMapping("addOrUpdate")
    public Map<String, Object> addOrUpdate(@ApiIgnore OaCar car, HttpServletRequest request) {
        //获取当前操作人
        rowMap(request);
        //判断当前操作人是否存在
        if (ObjectUtils.isEmpty(personnel)) {
            return tools.rowMap(map, 0, null);
        }
        try {
            if (car.getPkCarId() == null || car.getPkCarId() < 1L) {
                car.setCreatedBy(personnel.getPersonnelName());
                //车辆新增
                row = carService.add(car, personnel);
            } else {
                // 修改人
                car.setUpdatedBy(personnel.getPersonnelName());
                // 修改时间
                car.setUpdatedTime(new Date());
                //方法修改
                row = carService.updateByPrimaryKeySelective(car);
            }

            //日志标题
            log.setLogTitle("车辆新增");
            //日志类型
            log.setLogType("1");
            //日志内容
            log.setLogBody(JSON.toJSON(car).toString());
            //存入日志信息 格式化返回信息
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            //报错信息收集
            addErrorLog(request, "车辆新增", e);
        }
        return map;
    }

    /**
     * 批量删除
     *
     * @param ids     车辆id集
     * @param request 服务器请求
     * @return 回调函数
     */
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "车辆批量id", dataType = "Long[]", paramType = "body", required = true),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "提交成功"),
    })
    @UserLoginToken
    @DeleteMapping("deleteAll")
    public Map<String, Object> deleteAll(@ApiIgnore @RequestParam(value = "ids[]", required = false) Long[] ids, HttpServletRequest request) {
        //获取当前登录人信息
        rowMap(request);
        //判断当前登陆人是否存在
        if (ObjectUtils.isEmpty(personnel)) {
            return tools.rowMap(map, 0, null);
        }
        try {
            //数组转化为集合
            List<Long> list = Arrays.asList(ids);
            //查询要删除得数据
            List<OaCar> dataDictionaries = carService.selectAll(list);
            //批量删除车辆
            row = carService.deleteAll(list);
            //日志标题
            log.setLogTitle("车辆批量删除");
            //日志内容
            log.setLogBody(JSON.toJSON(dataDictionaries).toString());
            //日志类型
            log.setLogType("1");
            //新增日志信息格式化返回值给前台
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            //收集错误信息
            addErrorLog(request, "车辆批量删除", e);
        }
        return map;
    }

    /**
     * id删除
     *
     * @param id      转正流程id
     * @param request 服务器请求
     * @return 回调函数
     */
    @ApiOperation(value = "id删除", notes = "id删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "车辆id", dataType = "Long", paramType = "path", required = true
            ),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "删除成功"),
    })
    @UserLoginToken
    @DeleteMapping("deleteById/{id}")
    public Map<String, Object> deleteById(@PathVariable(value = "id", required = false) Long id, HttpServletRequest request) {
        rowMap(request);
        if (ObjectUtils.isEmpty(personnel)) {
            return tools.rowMap(map, 0, null);
        }
        try {
            //根据id查询
            OaCar flow = carService.selectByPrimaryKey(id);
            //根据id删除
            row = carService.deleteByPrimaryKey(id);
            //日志标题
            log.setLogTitle("车辆删除");
            //日志内容
            log.setLogBody(JSON.toJSON(flow).toString());
            //日志类型
            log.setLogType("1");
            //新增日志信息 格式化返回参数
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request, "车辆删除", e);
        }
        return map;
    }

    /**
     * 优化代码 获取当前登陆人信息
     *
     * @param request 服务器请求
     */
    private void rowMap(HttpServletRequest request) {
        //新建返回Map模型
        map = new HashMap<>(16);
        //获取登陆人信息
        personnel = (OaPersonnel) request.getSession().getAttribute("user");
        //为空则清空map
        if (ObjectUtils.isEmpty(personnel)) {
            return;
        }
        //新建日志
        log = new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(personnel.getPersonnelName());
    }


    /**
     * 收集报错日志
     *
     * @param request 请求 用于得到当前登录人和ip地址
     * @param title   模块标题
     * @param e       异常参数
     */
    private void addErrorLog(HttpServletRequest request, String title, Exception e) {
        //后台打印报错信息
        e.printStackTrace();
        //获取当前操作人
        personnel = (OaPersonnel) request.getSession().getAttribute("user");
        //新建日志
        log = new OaLog();
        //日志类型
        log.setLogType("0");
        //日志内容
        log.setLogBody(e.getLocalizedMessage());
        //日志标题
        log.setLogTitle(title);
        //请求地址
        log.setLogIp(request.getRemoteAddr());
        //判断当前登陆人是否存在
        if (ObjectUtils.isEmpty(personnel)) {
            //当前操作人名称
            log.setCreatedBy(personnel.getPersonnelName());
        }
        //存入报错日志
        tools.errorMap(log);
    }

    /**
     * 日期格式化
     *
     * @param binder 服务器参数转换器
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // true:允许输入空值，false:不能为空值
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

}
